<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination } from 'element-plus';

// 部门数据
const deptData = ref([]);

// 搜索条件
const searchForm = reactive({
  name: '',
  status: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的部门ID
const currentDeptId = ref(null);
// 表单数据
const formData = reactive({
  name: '',
  description: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 50, message: '部门名称长度在1到50个字符之间', trigger: 'blur' }
  ]
};

// 表单引用
const deptFormRef = ref(null);

// 加载部门数据
const loadDeptData = () => {
  // 模拟API请求，使用静态数据
  deptData.value = [
    {
      id: 1,
      name: '测试1部',
      status: '停用',
      lastModifiedTime: '2025-10-03 22:34:05'
    },
    {
      id: 2,
      name: '食空部',
      status: '正常',
      lastModifiedTime: '2025-10-03 22:35:59'
    },
    {
      id: 3,
      name: '厨师部',
      status: '停用',
      lastModifiedTime: '2025-10-03 22:48:07'
    },
    {
      id: 4,
      name: '测试0部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:21:18'
    },
    {
      id: 5,
      name: '测试3部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:21:01'
    },
    {
      id: 6,
      name: '测试2部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:21:01'
    },
    {
      id: 7,
      name: '测试7部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:52'
    },
    {
      id: 8,
      name: '测试6部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:43'
    },
    {
      id: 9,
      name: '测试5部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:33'
    },
    {
      id: 10,
      name: '测试4部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:24'
    },
    {
      id: 11,
      name: '测试8部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:15'
    },
    {
      id: 12,
      name: '测试9部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:20:06'
    },
    {
      id: 13,
      name: '测试10部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:19:57'
    },
    {
      id: 14,
      name: '测试11部',
      status: '正常',
      lastModifiedTime: '2025-09-29 19:19:48'
    }
  ];
};

// 计算总数
const total = computed(() => deptData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return deptData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  searchForm.name = '';
  searchForm.status = '';
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentDeptId.value = row.id;
  formData.name = row.name;
  formData.description = row.description || '';
  dialogVisible.value = true;
};

// 删除部门
const deleteDept = (row) => {
  ElMessageBox.confirm('确定要删除该部门吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = deptData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      deptData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存部门
const saveDept = () => {
  deptFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = deptData.value.findIndex(item => item.id === currentDeptId.value);
        if (index !== -1) {
          deptData.value[index].name = formData.name;
          deptData.value[index].lastModifiedTime = now;
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newDept = {
          id: Date.now(), // 模拟生成唯一ID
          name: formData.name,
          status: '正常',
          lastModifiedTime: now
        };
        deptData.value.push(newDept);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (deptFormRef.value) {
    deptFormRef.value.resetFields();
  }
  formData.name = '';
  formData.description = '';
  currentDeptId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadDeptData();
});
</script>

<template>
  <div class="dept-container">
    <div class="search-bar">
      <div class="search-item">
        <label>部门名称</label>
        <ElInput v-model="searchForm.name" placeholder="请输入部门名称" style="width: 200px;"></ElInput>
      </div>
      <div class="search-item">
        <label>状态</label>
        <ElSelect v-model="searchForm.status" placeholder="请选择" style="width: 150px;">
          <ElOption label="正常" value="正常"></ElOption>
          <ElOption label="停用" value="停用"></ElOption>
        </ElSelect>
      </div>
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton @click="handleReset">清空</ElButton>
    </div>
    
    <div class="dept-header">
      <ElButton type="primary" @click="openAddDialog">+ 添加部门</ElButton>
    </div>
    
    <div class="dept-content">
      <ElTable 
        v-if="deptData.length > 0"
        :data="currentPageData" 
        style="width: 100%; height: calc(100% - 60px);"
        stripe
        border
        fit
      >
        <ElTableColumn type="index" label="序号" min-width="80"></ElTableColumn>
        <ElTableColumn 
          prop="name" 
          label="部门名称" 
          min-width="200"
        />
        <ElTableColumn prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <span :class="['status-badge', row.status === '正常' ? 'status-normal' : 'status-disabled']">
              {{ row.status }}
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn 
          prop="lastModifiedTime" 
          label="最后修改时间" 
          min-width="180"
        />
        <ElTableColumn 
          label="操作" 
          min-width="120" 
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <ElButton 
                type="text" 
                @click="openEditDialog(row)"
                size="small" 
                style="color: #409EFF;"
              >
                修改
              </ElButton>
              <ElButton 
                type="text" 
                @click="deleteDept(row)"
                size="small" 
                style="color: #F56C6C;"
              >
                删除
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-else class="empty-data">暂无部门数据</div>
      
      <!-- 分页组件 -->
      <div class="pagination">
        <span class="total">共 {{ total }} 条</span>
        <ElSelect v-model="pageSize" @change="handleSizeChange" style="width: 100px;">
          <ElOption label="10条/页" value="10"></ElOption>
          <ElOption label="20条/页" value="20"></ElOption>
          <ElOption label="50条/页" value="50"></ElOption>
        </ElSelect>
        <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          layout="prev, pager, next, jumper"
        ></ElPagination>
      </div>
    </div>
    
    <!-- 添加/编辑部门对话框 -->
    <ElDialog
      :title="editMode ? '编辑部门' : '添加部门'"
      v-model="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <ElForm
        ref="deptFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <ElFormItem label="部门名称" prop="name">
          <ElInput v-model="formData.name" placeholder="请输入部门名称" />
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <ElButton @click="closeDialog">取消</ElButton>
        <ElButton type="primary" @click="saveDept">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 确保body没有默认margin */
:global(body) {
  margin: 0;
  padding: 0;
}

.dept-container {
  padding: 15px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

/* 搜索栏样式 */
.search-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  white-space: nowrap;
  font-weight: 500;
  color: #606266;
}

.dept-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

/* 状态标签样式 */
.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-normal {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-disabled {
  background-color: #fef0f0;
  color: #f56c6c;
}

.dept-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.empty-data {
  text-align: center;
  padding: 100px 0;
  color: #999;
  font-size: 16px;
}

/* 自定义表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  padding: 15px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-button--small) {
  padding: 8px 16px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  gap: 15px;
  flex-shrink: 0;
}

.pagination .total {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

/* 操作按钮样式 */
:deep(.el-button--text) {
  padding: 8px 10px;
}
</style>